package com.tsing.cloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author TheTsing
 * @version 1.0
 * @date 2021/11/8 15:02
 */
@Service
public class PaymentService {

    /**
     * 设置自身调用超时时间的峰值，峰值内可以正常运行，超过了需要有兜底方法处理，作服务降级fallback
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public String paymentInfo_TimeOut() {
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "8001成功";
    }

    //限流器兜底方法
    public String paymentInfo_TimeOutHandler() {
        return "8001系统繁忙";
    }

    //服务熔断
    @HystrixCommand(fallbackMethod = "circuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),                      //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),         //一个统计窗口内熔断触发的最小个数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),   //熔断多少秒后去尝试请求
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),       //失败率达到多少百分比后熔断（10次有6次或以上失败，就会触发熔断）
    })
    public String breaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        return "成功";
    }

    //熔断器兜底方法
    public String circuitBreaker_fallback(Integer id) {
        return "id不能为负数，请稍后重试";
    }
}
